package org.example.platform;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class myController {

    @Autowired
    MyService myService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/a")
    public String getA() {
        return "hello";

    }

    @PostMapping("/update")
    public String update(Depart depart) {
        myService.update(depart);
        return "hello";

    }

    @PostMapping("/shenHe")
    public String shenHe(Depart depart) {
        myService.shenHe(depart);
        return "hello";

    }

    @GetMapping("/sendMsg")
    public String sendMsg(String phone, HttpSession session) {
        if(!Validator.isMobile(phone)){
            return "手机号格式错误";
        }
        String num = RandomUtil.randomNumbers(6);
        session.setAttribute("code",num);
        return num;
    }

    @GetMapping("/login")
    public String login(String phone,String code, HttpSession session) {
        if(!Validator.isMobile(phone)){
            return "手机号格式错误";
        }
        if(null == code || !session.getAttribute("code").equals(code)){
            return "验证码格式错误";
        }
      // 校验用户是否存在
        User user = new User();
        user.setPhone(phone);
        user.setId(111);
        user.setName("erre");
        session.setAttribute("user",user);
        return "登录成功";
    }


    @GetMapping("/queryById")
    public String queryById(int id) {
       // 从redis查询缓存
        String key = ""+id;
        String info = stringRedisTemplate.opsForValue().get(key);
        // 判断是否存在
        if(!StrUtil.isBlank(info)){
            // 存在返回
            User user = JSONUtil.toBean(info, User.class);
            return user.toString();
        }

        // 不存在查数据库
        User user = new User();
        user.setName("ssss");
        user.setCode("333333");
        user.setId(22);
        user.setPhone("5223666666666");

        // 写入缓存
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(user));
        return user.toString();
    }






    @GetMapping("/update")
    public String update(int id) {
        // 更新数据
        // 更新时删除缓存
        stringRedisTemplate.delete(id+"");
        return "ok";
    }







}
